/**
 * 初始化 Easyui Datagrid 的封装
 *
 * 约定：toolbar的id为 (bstableId + "Toolbar")
 *
 * @author wanqing
 */
(function () {
    var HISUITable = function (bstableId, url, columns) {
        this.btInstance = null;					//jquery和BootStrapTable绑定的对象
        this.bstableId = bstableId;
        this.url = url;
        this.method = "post";
        this.paginationType = "server";			//默认分页方式是服务器分页,可选项"client"
        this.toolbarId = bstableId + "Toolbar";
        this.columns = columns;
        this.data = {};
        this.queryParams = {}; // 向后台传递的自定义参数
        this.showColumns = true;
        this.showRefresh = true;
        this.sortName = undefined;
        this.sortOrder = "desc";
        this.search = false;      		//是否显示表格搜索，此搜索是客户端搜索，不会进服务端
        this.height = 0;//默认表格高度665
        this.width=0;
        this.subHeight = 0;
        this.editIndex = undefined; //当前编辑得行标号
        this.modifyBeforeRow = {};   //修改前得行内容
        this.modifyAfterRow= {};	 //修改后得行内容
        this.title="库表设计";
        this.rownumbers = false;
    };

    HISUITable.prototype = {
        /**
         * 初始化bootstrap table
         */
        init: function () {
            if(this.height==0){
                this.autoHeight();
            }
            var tableId = this.bstableId;
            var _queryParams = this.queryParams;
            this.btInstance =
                $('#' + tableId).datagrid({
                    contentType: "application/x-www-form-urlencoded",
                    idField:'id',
                    autoRowHeight:false,
                    url: this.url,				//请求地址
                    method: this.method,		//ajax方式,post还是get
                    height:this.height,
                    width:this.width,
                    //title:this.title,
                    toolbar: "#" + this.toolbarId,//顶部工具条
                    striped: false,     			//是否显示行间隔色
                    pagination: true,     		//是否显示分页（*）
                    fitColumns:true,
                    sortName: this.sortName,      		//排序字段
                    sortOrder: this.sortOrder,     		//排序方式
                    pageNumber: 1,      			//初始化加载第一页，默认第一页
                    pageSize: 30,      			//每页的记录行数（*）
                    pageList: [30,50],  	//可供选择的每页的行数（*）
                    singleSelect:true,				//只允许选中一行
                    queryParams: function (param) {
                        return $.extend(_queryParams, param);
                    }, // 向后台传递的自定义参数
                    rownumbers: this.rownumbers,
                    columns: this.columns,		//列数组
                    loadMsg:'数据加载中,请稍候……',
                    onDblClickRow:function(index,data){
                        if (this.editIndex!=undefined&&this.editIndex != index) {
                            //如果用户点击的行与之前的行不一样，则先关掉之前行的编辑
                            $('#' + tableId).datagrid('endEdit', this.editIndex);
                            $('#' + tableId).datagrid('cancelEdit', this.editIndex);
                            $('#' + tableId).datagrid('selectRow', index).datagrid('beginEdit',index);
                            this.editIndex = index;
                            modifyBeforeRow = $.extend({},$('#' + tableId).datagrid('getRows')[this.editIndex]);
                            //判断字段是否已同步，如果已同步，则不能对字段进行修改
                            if(modifyBeforeRow.isSync==1){
                                Sys.info("该字段已经同步,现在禁止编辑！");
                                $('#' + tableId).datagrid('cancelEdit', this.editIndex);
                                return;
                            }
                        }else{
                            this.editIndex = index;
                            var curRow=$('#' + tableId).datagrid('getRows')[this.editIndex];
                            if(curRow.isSync==1){
                                Sys.info("该字段已经同步,现在禁止编辑！");
                                $('#' + tableId).datagrid('cancelEdit', this.editIndex);
                                return;
                            }else{
                                $('#' + tableId).datagrid('selectRow', index).datagrid('beginEdit',index);
                                $('#' + tableId).datagrid('selectRow', this.editIndex);
                            }
                        }
                    }
                });
            return this;
        },
        autoHeight:function(){
            var t_top = 53;
            var b_height = document.documentElement.clientHeight;
            var b_width  = $(this).parent().clientWidth;//获取父元素宽度
            this.height = b_height-t_top+this.subHeight;
            this.width =b_width;
        },
        setSubHeight:function(height){
            this.subHeight = height;
        },
        /**
         * 是否显示表格搜索，此搜索是客户端搜索，不会进服务端
         * @param param
         */
        setSearch: function (search) {
            this.search = search;
        },
        /**
         * 是否显示刷新按钮
         * @param param
         */
        setShowRefresh: function (showRefresh) {
            this.showRefresh = showRefresh;
        },
        /**
         * 是否显示所有的列
         * @param param
         */
        setShowColumns: function (showColumns) {
            this.showColumns = showColumns;
        },
        /**
         * 向后台传递的自定义参数
         * @param param
         */
        setQueryParams: function (param) {
            this.queryParams = param;
        },
        /**
         * 设置分页方式：server 或者 client
         */
        setPaginationType: function (type) {
            this.paginationType = type;
        },
        /**
         * 设置默认排序字段
         */
        setSortName: function (sortName) {
            this.sortName = sortName;
        },
        /**
         * 设置默认排序字段
         */
        setSortOrder: function (sortOrder) {
            this.sortOrder = sortOrder?sortOrder:"desc";
        },

        setSort: function (sortName,sortOrder) {
            this.sortName = sortName;
            this.sortOrder = sortOrder?sortOrder:"desc";
        },


        /**
         * 设置ajax post请求时候附带的参数
         */
        set: function (key, value) {
            this.queryParams[key] = (typeof value == "undefined") ? $("#" + key).val() : value;
            return this;
        },

        /**
         * 清空ajax post请求参数
         */
        clear: function () {
            this.queryParams = {};
            return this;
        },

        /**
         * 刷新 datagrid 表格
         * Refresh the remote server data,
         * you can set {silent: true} to refresh the data silently,
         * and set {url: newUrl} to change the url.
         * To supply query params specific to this request, set {query: {foo: 'bar'}}
         */
        refresh: function (parms) {
            if (typeof parms != "undefined") {
                this.btInstance.datagrid(parms);
            } else {
                this.btInstance.datagrid("reload");
            }
        },
        acceptChanges:function(){
            var tableId = this.bstableId;
            $('#' + tableId).datagrid('acceptChanges');
        },
        delRow:function(){
            var tableId = this.bstableId;
            var rows = $('#' + tableId).datagrid('getSelections');
            if(rows.length>0){
                for(var i=0;i<rows.length;i++){
                    var index=$('#' + tableId).datagrid('getRowIndex',rows[i]);
                    $('#' + tableId).datagrid('deleteRow',index);
                }
            }
        },
        /**
         * 设置标题
         */
        setTitle:function(title){
            this.title=title;
        },
        /**
         * 是否显示行号
         */
        setRowNumbers:function (showRowNum) {
            this.rownumbers = showRowNum;
        }
    };

    window.HISUITable = HISUITable;

}());